package qeug.shsh.opplugin;

import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.form.FormShowParameter;
import kd.bos.form.control.Button;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.EventObject;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.opplugin
 * @className: FundSelectPluginEx
 * @author: wenyx
 * @description: 查询资金计划
 * @date: 2024/2/29 16:53
 * @version: 1.0
 * 说明：查询资金计划页面插件，仅在付款申请单中打开页面进行下面逻辑，
 */
public class FundSelectPluginEx extends AbstractFormPlugin implements Plugin {

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("btncancel");
        this.addClickListeners("btnok");
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Button source = (Button) evt.getSource();
        String key = source.getKey();
        FormShowParameter formShowParameter = this.getView().getFormShowParameter();
        String opreationType = formShowParameter.getCustomParam("opreationType");//操作类型：view（查看）、open（选择）
        if ("btnok".equals(key)) {
            if ("view".equals(opreationType)) {
                this.getView().close();
                return;
            }
            EntryGrid entryGrid = this.getControl("qeug_entryentity");
            int[] selectRows = entryGrid.getSelectRows();
            int count = selectRows.length;
            //分录行数只有一条的时候才能通过接下来两个if
            if (count == 0) {
                this.getView().showErrorNotification("请选择一条分录!");
                return;
            }
            if (count > 1) {
                this.getView().showErrorNotification("只能选择一条分录!");
                return;
            }
            DynamicObjectCollection qeug_entryentity = getModel().getEntryEntity("qeug_entryentity");//查询资金计划分录
            int vale = getModel().getEntryCurrentRowIndex("qeug_entryentity");//所选的分录行
            DynamicObject dynamicObject = qeug_entryentity.get(vale);
            boolean qeug_isg6 = dynamicObject.getBoolean("qeug_isg6");
            if (!qeug_isg6) {
                this.getView().showErrorNotification("资金计划未同步G6，不可引用!");
                return;
            } else {
                this.getView().returnDataToParent(dynamicObject);
            }
        }
        this.getView().close();
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        try {
            super.afterCreateNewData(e);
            FormShowParameter formShowParameter = this.getView().getFormShowParameter();
            JSONObject company = formShowParameter.getCustomParam("company");//费用承担公司（付款申请）
            JSONObject costDept = formShowParameter.getCustomParam("qeug_costdept");//一级承担部门（付款申请）
            String entryId = formShowParameter.getCustomParam("entryid").toString();//资金计划行号（付款申请）
            String bizdate = formShowParameter.getCustomParam("bizdate");//申请日期（付款申请）
            String opreationType = formShowParameter.getCustomParam("opreationType");//操作类型：view（查看）、open（选择）（付款申请）

            long companyId = company.getLong("id");//公司id
            long deptId = costDept.getLong("id");//一级承担部门id

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date bizDate = dateFormat.parse(bizdate);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(bizDate);

            calendar.set(Calendar.DAY_OF_MONTH, 1);
            Date monthStartDate = calendar.getTime();
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date monthEndDate = calendar.getTime();

            QFilter[] filters = new QFilter[]{
                    new QFilter("org.id", QCP.equals, companyId),//费用承担公司id（资金计划）
                    new QFilter("qeug_costdept.id", QCP.equals, deptId),//一级承担部门id
                    new QFilter("qeug_yearmonth", QCP.large_equals, monthStartDate),//大于等于开始年月
                    new QFilter("qeug_yearmonth", QCP.less_equals, monthEndDate),//小于等于结束年月
                    new QFilter("billstatus", QCP.equals, "C")//已审核单据
            };
            DynamicObject singleFundPlan = BusinessDataServiceHelper.loadSingle("qeug_fundplan", filters);//资金计划
            if (singleFundPlan == null) {
                this.getView().showErrorNotification("该公司部门下没有资金计划或没有当前时间的资金计划！");
                return;
            }
//            DynamicObject[] fundPlans = BusinessDataServiceHelper.load("qeug_fundplan",
//                    "billno,entryentity,entryentity.id,qeug_paytype,qeug_planpaydate,qeug_requestpaynum,qeug_person,qeug_supplier,qeug_customer," +
//                            "qeug_bank,qeug_fundtype,qeug_fundcate,qeug_fundsuse,qeug_sffs,qeug_tzproject,qeug_contractnum,qeug_currency,qeug_ysbankamount,entryentity.qeug_yshpamount" +
//                            "entryentity.qeug_ysxyzamount,qeug_bankamount,qeug_hpamount,qeug_xyzamount,qeug_localamount,qeug_remark,qeug_isg6",
//                    filters);//资金计划
            DynamicObject[] fundPlans = BusinessDataServiceHelper.load("qeug_fundplan","billno", filters);//资金计划
            DynamicObjectCollection planEntries = (DynamicObjectCollection) this.getModel().getValue("qeug_entryentity");//查询资金计划分录
            planEntries.clear();
            DynamicObjectType entryType = planEntries.getDynamicObjectType();
            int matchCount = 0;
            for (DynamicObject fundPlan : fundPlans) {
                String billNo = fundPlan.getString("billno");//单据编码
                QFilter[] qFilter = new QFilter[]{
                        new QFilter("billno", QCP.equals, billNo)};
                DynamicObject fundPlan1 = BusinessDataServiceHelper.loadSingle("qeug_fundplan", qFilter);
                DynamicObjectCollection entryEntities = fundPlan1.getDynamicObjectCollection("entryentity");//资金计划分录
                if ("view".equals(opreationType)) {
                    //查看资金计划
                    for (DynamicObject entryEntity : entryEntities) {
                        if (entryId.equals(entryEntity.get("id").toString())) {
                            DynamicObject newEntry = new DynamicObject(entryType);
                            newEntry.set("qeug_number", billNo);//单据编码
                            newEntry.set("qeug_paytype", entryEntity.get("qeug_paytype"));//付款类别
                            newEntry.set("qeug_planpaydate", entryEntity.get("qeug_planpaydate"));//计划付款日期
                            newEntry.set("qeug_requestpaynum", entryEntity.get("qeug_requestpaynum"));//付款申请单号
                            newEntry.set("qeug_person", entryEntity.get("qeug_person"));//业务员
                            newEntry.set("qeug_supplier", entryEntity.get("qeug_supplier"));//收款单位
                            newEntry.set("qeug_customer", entryEntity.get("qeug_customer"));//客户
                            newEntry.set("qeug_bank", entryEntity.get("qeug_bank"));//收款银行
                            newEntry.set("qeug_fundtype", entryEntity.get("qeug_fundtype"));//资金类别
                            newEntry.set("qeug_fundcate", entryEntity.get("qeug_fundcate"));//款项大类
                            newEntry.set("qeug_fundsuse", entryEntity.get("qeug_fundsuse"));//款项用途
                            newEntry.set("qeug_sffs", entryEntity.get("qeug_sffs"));//结算方式
                            newEntry.set("qeug_tzproject", entryEntity.get("qeug_tzproject"));//投资项目
                            newEntry.set("qeug_contractnum", entryEntity.get("qeug_contractnum"));//合同号
                            newEntry.set("qeug_currency", entryEntity.get("qeug_currency"));//币种
                            newEntry.set("qeug_bankamount", entryEntity.get("qeug_ysbankamount"));//银行存款
                            newEntry.set("qeug_amountfield", entryEntity.get("qeug_yshpamount"));//承兑汇票
                            newEntry.set("qeug_amountfield1", entryEntity.get("qeug_ysxyzamount"));//信用证
                            newEntry.set("qeug_decimalfield", entryEntity.get("qeug_bankamount"));//剩余银行存款
                            newEntry.set("qeug_hpamount", entryEntity.get("qeug_hpamount"));//剩余承兑汇票
                            newEntry.set("qeug_xyzamount", entryEntity.get("qeug_xyzamount"));//剩余信用证
                            newEntry.set("qeug_localamount", entryEntity.get("qeug_localamount"));//原币金额
                            newEntry.set("qeug_textfield", entryEntity.get("qeug_remark"));//说明
                            newEntry.set("qeug_isg6", entryEntity.get("qeug_isg6"));//是否已推送G6
                            newEntry.set("qeug_entryid", entryEntity.get("id"));//资金计划分录行id
                            planEntries.add(newEntry);
                            matchCount++;
                            break;
                        }
                    }
                } else {
                    //选择资金计划
                    for (DynamicObject entryEntity : entryEntities) {
                        DynamicObject newEntry = new DynamicObject(entryType);
                        newEntry.set("qeug_number", billNo);//单据编码
                        newEntry.set("qeug_paytype", entryEntity.get("qeug_paytype"));//付款类别
                        newEntry.set("qeug_planpaydate", entryEntity.get("qeug_planpaydate"));//计划付款日期
                        newEntry.set("qeug_requestpaynum", entryEntity.get("qeug_requestpaynum"));//付款申请单号
                        newEntry.set("qeug_person", entryEntity.get("qeug_person"));//业务员
                        newEntry.set("qeug_supplier", entryEntity.get("qeug_supplier"));//收款单位
                        newEntry.set("qeug_customer", entryEntity.get("qeug_customer"));//客户
                        newEntry.set("qeug_bank", entryEntity.get("qeug_bank"));//收款银行
                        newEntry.set("qeug_fundtype", entryEntity.get("qeug_fundtype"));//资金类别
                        newEntry.set("qeug_fundcate", entryEntity.get("qeug_fundcate"));//款项大类
                        newEntry.set("qeug_fundsuse", entryEntity.get("qeug_fundsuse"));//款项用途
                        newEntry.set("qeug_sffs", entryEntity.get("qeug_sffs"));//结算方式
                        newEntry.set("qeug_tzproject", entryEntity.get("qeug_tzproject"));//投资项目
                        newEntry.set("qeug_contractnum", entryEntity.get("qeug_contractnum"));//合同号
                        newEntry.set("qeug_currency", entryEntity.get("qeug_currency"));//币种
                        newEntry.set("qeug_bankamount", entryEntity.get("qeug_ysbankamount"));//银行存款
                        newEntry.set("qeug_amountfield", entryEntity.get("qeug_yshpamount"));//承兑汇票
                        newEntry.set("qeug_amountfield1", entryEntity.get("qeug_ysxyzamount"));//信用证
                        newEntry.set("qeug_decimalfield", entryEntity.get("qeug_bankamount"));//剩余银行存款
                        newEntry.set("qeug_hpamount", entryEntity.get("qeug_hpamount"));//剩余承兑汇票
                        newEntry.set("qeug_xyzamount", entryEntity.get("qeug_xyzamount"));//剩余信用证
                        newEntry.set("qeug_localamount", entryEntity.get("qeug_localamount"));//原币金额
                        newEntry.set("qeug_textfield", entryEntity.get("qeug_remark"));//说明
                        newEntry.set("qeug_isg6", entryEntity.get("qeug_isg6"));//是否已推送G6
                        newEntry.set("qeug_entryid", entryEntity.get("id"));//资金计划分录行id
                        planEntries.add(newEntry);
                    }
                }
            }
            if (matchCount == 0 && "view".equals(opreationType)) {
                this.getView().showErrorNotification("未查询到资金计划！");
                return;
            }
            this.getModel().setValue("qeug_comapany", companyId);//公司
            this.getModel().setValue("qeug_admin", deptId);//一级承担部门
            this.getModel().setValue("qeug_date", bizDate);//年月
            this.getModel().setValue("qeug_entryentity", planEntries);//查询资金计划分录
        } catch (ParseException ex) {
            throw new RuntimeException(ex);
        }
    }
}
